﻿using LYR_RPA.models.entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LYR_RPA.utils
{
    public class HttpClientUtils
    {

        public static readonly HttpClientUtils httpClientUtils = new HttpClientUtils();

        private HttpClientUtils() { }

        static HttpClientUtils() { }
        public static HttpClientUtils HttpClient()
        {
            return httpClientUtils;
        }

        public async Task<string> Login(string ip,string port,string username,string password)
        {

            var values = new Dictionary<string, string>()
            {
               { "username", username },
               { "password", password }
            };
            
            // 将字典转换为 JSON 字符串
            var json = JsonConvert.SerializeObject(values);
            // 设置请求头为 application/json
            using (HttpClient client = new HttpClient())
            {
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                client.DefaultRequestHeaders.Add("Tenant-Id", "1");
                client.Timeout = TimeSpan.FromSeconds(5);
                Console.WriteLine($"http://{ip}:{port}/admin-api/system/auth/login");
                try
                {
                    var response = await client.PostAsync($"http://{ip}:{port}/admin-api/system/auth/login", content);
                    var responseStr = await response.Content.ReadAsStringAsync();
                    if (response.IsSuccessStatusCode)
                    {
                        Result<Login> result = JSONUtils.StringToObject<Result<Login>>(responseStr);
                        Console.WriteLine(responseStr);
                        if (result.Code == 0 && result.Data != null)
                        {
                            return result.Data.AccessToken;
                        }

                    }
                }catch (Exception ex)
                {
                    Console.WriteLine($"登录出现异常：{ex.ToString()}");
                }
                
            }
            return "";
        }
        public static async Task<string> GetRequextAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetAsync(url);
                Console.WriteLine(response.Content);
            }
                
            return "";
        }
    }
}
